<template>
  <div>
    <el-form class="query-form" ref="queryForm" size="small" :model="queryParams" :inline="true">
      <el-form-item label="所属项目" prop="appids">
        <el-select v-model="queryParams.appids" multiple clearable placeholder="全部" @change="handleQuery">
          <el-option v-for="item in permission_projectList" :key="item.app_id" :label="item.name" :value="item.app_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="套餐内容" prop="order_name">
        <el-select v-model="queryParams.order_name" placeholder="请选择" filterable @change="handleQuery">
          <el-option label="全部" :value="null" />
          <el-option v-for="item in productData" :key="item.id" :label="item.show_name" :value="item.show_name" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status" class="small-query">
        <el-select v-model.number="queryParams.status" placeholder="请选择" @change="handleQuery">
          <el-option key="all" label="全部" :value="null" />
          <el-option v-for="([key, value], index) in invoiceStatus" :key="index" :label="value.desc" :value="key" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单金额">
        <el-input-number v-model.trim="numberRange.pay_amount_begin" placeholder="最低价" size="small" :precision="2"
          style="width: 83px" />
        -
        <el-input-number v-model.trim="numberRange.pay_amount_end" placeholder="最高价" size="small" :precision="2"
          style="width: 83px" />
      </el-form-item>
      <el-form-item class="big-query" label="付款日期">
        <el-date-picker v-model="payDateRange" type="daterange" value-format="yyyy-MM-dd" range-separator="~"
          start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery" style="width: 210px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="申请日期">
        <el-date-picker v-model="submitDateRange" type="daterange" value-format="yyyy-MM-dd"
          range-separator="~" start-placeholder="开始日期" end-placeholder="结束日期" @change="handleQuery" style="width: 210px;">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="输入发票抬头、税号、订单号" size="small" style="width:240px" clearable
          @keyup.enter.native="handleQuery" @clear="handleQuery" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
        <el-button size="small" type="success" :loading="exportLoading" @click="exportCsv">导出全部</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" style="margin-bottom: 15px;" :data="invoiceList">
      <el-table-column label="订单号" min-width="200" prop="order_id" fixed="left" />
      <el-table-column label="订单金额" width="100" prop="amount">
        <template #default="{ row }">
          {{ row.amount | formatMoney }}
        </template>
      </el-table-column>
      <el-table-column label="发票类型" min-width="100" prop="invoice_type">
        <template slot-scope="scope">
          <span>{{scope.row.invoice_type === 26 ? '普通发票':'专用发票'}}</span>
        </template>
      </el-table-column>
      <el-table-column label="发票抬头" width="160" prop="invoice_header" />
      <el-table-column label="税号" width="180" prop="tax_number" />
      <el-table-column label="收票邮箱" width="160" prop="email" />
      <el-table-column label="套餐内容" width="160" prop="order_name" />
      <el-table-column label="开票状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="invoiceStatus.get(scope.row.status).tagType" disable-transitions>{{
            invoiceStatus.get(scope.row.status).desc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="付款时间" width="180" prop="pay_time">
        <template slot-scope="scope">
          <span>{{ scope.row.pay_time|parseTime() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="申请时间" width="180" prop="submit_time">
        <template slot-scope="scope">
          <span>{{ scope.row.submit_time|parseTime() }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户备注" width="160" prop="remark" />
      <el-table-column label="操作备注" width="160" prop="admin_remark" />
      <el-table-column label="订单状态" width="100">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.order_status" :type="orderStatus.get(scope.row.order_status).tagType"
            disable-transitions>{{ orderStatus.get(scope.row.order_status).desc }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="160" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" :disabled="[1, 4].indexOf(scope.row.status) === -1"
            @click="auditOrDumpingShow(scope.row, 'check')">审核</el-button>
          <!-- <el-button size="small" type="text" :disabled="[5, 6].indexOf(scope.row.status) > -1"
            @click="handleDetail(scope.row, 'edit')">修改</el-button> -->
          <el-button size="small" type="text" :disabled="[4, 5, 6, 7, 8].indexOf(scope.row.status) > -1"
            @click="auditOrDumpingShow(scope.row, 'cancel')">报废</el-button>
          <el-button size="small" type="text" @click="handleDetail(scope.row, 'detail')">详情</el-button>
          <!-- <el-button size="small" type="text" @click="handleDel(scope.row)">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination v-if="total > 0" :total="total" layout="total,slot,sizes,prev,pager,next,jumper"
      :page.sync="queryParams.page" :limit.sync="queryParams.page_size" @pagination="getList">
    </pagination>
    <!-- 修改发票申请|详情 -->
    <invoiceDetail :open.sync="open" :openType="openType" :row="formData"  @handleSuccess="getList" />
    <!-- 审核|报废 -->
    <auditOrDumping :open="auditOrDumpingOpen" :openType="openType" :row="formData" @handleSuccess="handleSuccess" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { listInvoice, invoiceDelete, invoiceExpose } from '@/api/invoice'
import { productList } from '@/api/member/product'
import { parseTime } from '@/utils'
import invoiceDetail from './components/invoice-detail.vue'
import auditOrDumping from './components/audit-dumping.vue'
import { getInvoiceStatus, getOrderStatus } from '@/constants/constant'
export default {
  name: 'Order',
  components: { invoiceDetail, auditOrDumping },
  data () {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 权益表格数据
      invoiceList: null,
      productData: [],
      // 是否显示弹出层
      open: false,
      auditOrDumpingOpen: false,
      invoiceStatus: null,
      orderStatus: null,
      // 表单参数
      formData: {},
      // 查询参数 - 支付时间
      payDateRange: [],
      // 查询参数 - 申请时间
      submitDateRange: null,
      // 查询参数
      queryParams: {
        page: 1,
        page_size: 10,
        order_name: null,
        status: null,
        submit_begin: null,
        submit_end: null,
        pay_time_begin: null,
        pay_time_end: null,
        pay_amount_begin: null,
        pay_amount_end: null,
        keyword: null,
        appids: null
      },
      // 查询数字区间参数
      numberRange: {
        pay_amount_begin: undefined,
        pay_amount_end: undefined
      },
      exportLoading: false,
      openType: 'edit'
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList'])
  },
  filters: {},
  created () {
    const now = parseTime(new Date(), '{y}-{m}-{d}')
    this.submitDateRange = [now, now]
    // this.payDateRange = [now, now]
    this.invoiceStatus = getInvoiceStatus()
    this.orderStatus = getOrderStatus()
    productList({ status: 10, page: 1, page_size: 1000, keyword: '' }).then(res => {
      this.productData = res.data.list || []
    })
    this.getList()
  },
  methods: {
    /** 查看详情 */
    handleDetail (row, type) {
      const params = {
        ...row,
        address: row.address || row.adrss,
        personal_name: row.invoice_issuer === 1 ? row.invoice_header : '',
        company_name: row.invoice_issuer === 2 ? row.invoice_header : ''
      }
      delete params.adrss
      this.formData = JSON.parse(JSON.stringify(params))
      this.open = true
      this.openType = type
    },
    auditOrDumpingShow (row, type) {
      this.formData = JSON.parse(JSON.stringify(row))
      this.auditOrDumpingOpen = true
      this.openType = type
    },
    handleSuccess () {
      this.open = false
      this.auditOrDumpingOpen = false
      this.getList()
    },
    getListApi () {
      this.mergeQueryParams()
      this.loading = true
      const params = { ...this.queryParams }
      params.appids = this.queryParams.appids?.join(',') || null
      return new Promise((resolve, reject) => {
        listInvoice(params).then(response => {
          const data = response.data || {}
          resolve(data.list)
          this.total = data.count || 0
        }).finally(() => {
          this.loading = false
        })
      })
    },
    /** 查询用户列表 */
    getList () {
      this.getListApi().then(res => {
        this.invoiceList = res
      })
    },

    /** 搜索按钮操作 */
    handleQuery () {
      let { queryParams, numberRange } = this
      Object.keys(numberRange).forEach(key => {
        const item = numberRange[key]
        this.queryParams[key] = item ? item * 100 : undefined
      })
      const isValid = this.validNumberRangeInput(queryParams, 'pay_amount_begin', 'pay_amount_end')
      if (!isValid) {
        this.msgError('请检查数字区间输入')
        return
      }
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      const now = parseTime(new Date(), '{y}-{m}-{d}')
      this.submitDateRange = [now, now]
      this.payDateRange = []
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 删除按钮操作 */
    handleDel ({ order_id }) {
      this.$confirm(`是否确认删除该开票申请`, '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        invoiceDelete({ order_id }).then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
      })
    },

    /** 点击-全部导出 */
    exportCsv () {
      this.mergeQueryParams()
      this.exportLoading = true
      const params = { ...this.queryParams }
      params.appids = this.queryParams.appids?.join(',') || null
      invoiceExpose(params).then(res => {
        const href = URL.createObjectURL(res)
        const link = document.createElement('a')
        link.download = '开票列表.csv'
        link.href = href
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        URL.revokeObjectURL(href)
      }).finally(() => {
        this.exportLoading = false
      })
    },

    /** 合并列表搜索条件 */
    mergeQueryParams () {
      let { payDateRange, submitDateRange } = this
      const createDate = this.addDateRange(submitDateRange, 'submit_begin', 'submit_end')
      const payDate = this.addDateRange(payDateRange, 'pay_time_begin', 'pay_time_end')
      Object.assign(this.queryParams, createDate, payDate)
    }
  }
}
</script>
